 //
//  AppDelegate.m
//  HappyStore
//
//  Created by 点点充 on 16/1/11.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "AppDelegate.h"
#import <BaiduMapAPI_Base/BMKMapManager.h>
#import <WeiboSDK.h>
#import "WXApi.h"
#import <TencentOpenAPI/TencentOAuth.h>

#import "MainTabBarController.h"
#import "addFriendVC.h"

#import "YZWelcomeController.h"

#import "BaiduMobStat.h"

#import "LSSimpleMessageVC.h"
//#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()<WeiboSDKDelegate,WXApiDelegate,RCIMConnectionStatusDelegate,
RCIMReceiveMessageDelegate,RCIMUserInfoDataSource>
{
    BMKMapManager *_mapManager;
    
}
@end

@implementation AppDelegate

-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
    
    //如果极简开发包不可用，会跳转支付宝钱包进行支付，需要将支付宝钱包的支付结果回传给开发包
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
//            NSLog(@"result = %@",resultDic);
            
            NSString *resultStatus = [resultDic valueForKey:@"resultStatus"];
            if ([resultStatus isEqualToString:@"9000"]) {
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"alipayResult" object:nil];
                
            } else if ([resultStatus isEqualToString:@"6001"]){
                
                allConstDict = nil;
                
                NSString *strMsg = @"您已取消支付";
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付情况" message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                
            }else if ([resultStatus isEqualToString:@"6002"] || [resultStatus isEqualToString:@"4000"] || [resultStatus isEqualToString:@"其他"]){
                
                allConstDict = nil;
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"alipayFailed" object:nil];
          
            }

        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
        
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
//            NSLog(@"result = %@",resultDic);
        }];
    }
    
        return [WeiboSDK handleOpenURL:url delegate:self] || [WXApi handleOpenURL:url delegate:self] || [TencentOAuth HandleOpenURL:url];
}

#pragma mark - 微信回调
- (void)onResp:(BaseResp*)resp
{
    if (resp.errCode==0) {
        SendAuthResp *send = (SendAuthResp *)resp;
        NSLog(@"%@",send.code);
        
        [self showRoundProgressWithTitle:@"请稍后..."];
        //获取token
        NSString *strURl = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd1dfc18de783fc62&secret=08aac233dbe8631301a6bf2fb8975813&code=%@&grant_type=authorization_code",send.code];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //很重要，去掉就容易遇到错误，暂时还未了解更加详细的原因
        [manager POST:strURl parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dicInfo = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSString *strURl1 = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",dicInfo[@"access_token"],dicInfo[@"openid"]];
            [manager POST:strURl1 parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dicUserInfo = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"%@",dicUserInfo);
                
                NSMutableDictionary *muDic1 = [NSMutableDictionary dictionary];
                [muDic1 setObject:dicUserInfo[@"nickname"] forKey:@"userName"];
                [muDic1 setObject:dicUserInfo[@"headimgurl"] forKey:@"headPhoto"];
                [muDic1 setObject:dicUserInfo[@"unionid"] forKey:@"threeKey"];
                [muDic1 setObject:@"1" forKey:@"threeType"];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"startLoginWeiChat" object:nil userInfo:muDic1];
                
                [self hideBubble];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

                [self showSingleIconBubble:error.localizedDescription];

            }];

            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            [self showSingleIconBubble:error.localizedDescription];

        }];
    }
    
}

#pragma mark - 微博回调
-(void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        if ((int)response.statusCode == 0)
        {
            NSDictionary *dic = @{@"userID":[(WBAuthorizeResponse *)response userID], @"accessToken" :[(WBAuthorizeResponse *)response accessToken]};
            NSLog(@"微博授权：%@",dic);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"startOtherLogin" object:nil userInfo:dic];
        }
    }
}

- (void)logout {

    if (self.window.rootViewController != nil) {
        
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];

        self.window.rootViewController = loginNAV;
    }
    [[RCIMClient sharedRCIMClient] disconnect:NO];
}


#pragma mark - RCIMConnectionStatusDelegate

/**
 *  网络状态变化。
 *
 *  @param status 网络状态。
 */
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status {
    if (status == ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"提示"
                              message:
                              @"您"
                              @"的帐号在别的设备上登录，您被迫下线！"
                              delegate:nil
                              cancelButtonTitle:@"知道了"
                              otherButtonTitles:nil, nil];
        [alert show];
        
        [self resetDefaults];
        [USER_DEFAULTS setObject:@"1" forKey:@"token"];
        [USER_DEFAULTS removeObjectForKey:@"userid"];
        [USER_DEFAULTS removeObjectForKey:@"token"];
        [USER_DEFAULTS removeObjectForKey:@"industry"];
        [USER_DEFAULTS removeObjectForKey:@"imToken"];
        [USER_DEFAULTS synchronize];
        
        [[RCIMClient sharedRCIMClient]
         logout];
        allConstMemberToken = nil;
        allConstMemberid = nil;
        
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        
        self.window.rootViewController = loginNAV;
        
    } else if (status == ConnectionStatus_TOKEN_INCORRECT) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
            
            self.window.rootViewController = loginNAV;
            
            UIAlertView *alertView =
            [[UIAlertView alloc] initWithTitle:nil
                                       message:@"Token已过期，请重新登录"
                                      delegate:nil
                             cancelButtonTitle:@"确定"
                             otherButtonTitles:nil, nil];
            [alertView show];
        });
    }
}

- (void)resetDefaults
{
    NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
    NSDictionary* dict = [defs dictionaryRepresentation];
    for(id key in dict) {
        [defs removeObjectForKey:key];
    }
    [defs synchronize];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [self startBaiduMobileStat];
    
    //创建数据库
    [MagicalRecord setupCoreDataStackWithStoreNamed:@"MyDatabase.sqlite"];
    
    NSString *key = @"CFBundleVersion";
    // 上一次的使用版本（存储在沙盒中的版本号）
    NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    // 当前软件的版本号（从Info.plist中获得）
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[key];
    

    if ([currentVersion isEqualToString:lastVersion]) { // 版本号相同：这次打开和上次打开的是同一个版本
        
        Person * person = [Person MR_findFirstByAttribute:@"userid"  withValue:[USER_DEFAULTS objectForKey:@"userid"]];
        NSLog(@"数据库查询结果 ---------------- %@",person);
        
        allConstMemberid = person.userid;
        allConstMemberToken = person.token;
        allConstMemberUserType = person.usertype;
        allConstMemberImgStr = [USER_DEFAULTS objectForKey:@"headPhoto"];
//        NSArray *personArr = [Person MR_findAll];
//        for (Person *tmp in personArr) {
//            [tmp MR_deleteEntity];
//        }
//        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];

        
        if (allConstMemberid) {
            
            [LSCoverUserInfo CoverUserInfo];
            
        }

    } else {
        
        //跳转到欢迎界面
        YZWelcomeController * welcomeVc = [[YZWelcomeController alloc]init];
        self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        self.window.rootViewController = welcomeVc;
        [self.window makeKeyAndVisible];
        
        // 将当前的版本号存进沙盒
        [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    // 初始化融云SDK
    //appKey  从融云开发者平台创建应用后获取到的App Key
    [[RCIM sharedRCIM] initWithAppKey:@"e5t4ouvptp00a"];
    [[RCIM sharedRCIM]registerMessageType:[LSSimpleMessageVC class]];
    
    [[RCIM sharedRCIM] setConnectionStatusDelegate:self];
    [[RCIM sharedRCIM] setReceiveMessageDelegate:self];
    [[RCIM sharedRCIM] setUserInfoDataSource:self];
    
    /**
     * 推送处理1
     */
    if ([application
         respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        //注册推送, 用于iOS8以及iOS8之后的系统
        UIUserNotificationSettings *settings = [UIUserNotificationSettings
                                                settingsForTypes:(UIUserNotificationTypeBadge |
                                                                  UIUserNotificationTypeSound |
                                                                  UIUserNotificationTypeAlert)
                                                categories:nil];
        [application registerUserNotificationSettings:settings];
    } else {
        //注册推送，用于iOS8之前的系统
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeAlert |
        UIRemoteNotificationTypeSound;
        [application registerForRemoteNotificationTypes:myTypes];
    }
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(didReceiveMessageNotification:)
     name:RCKitDispatchMessageNotification
     object:nil];
    
    if ([USER_DEFAULTS objectForKey:@"imToken"]) {
        
        [[RCIM sharedRCIM] connectWithToken:[USER_DEFAULTS objectForKey:@"imToken"] success:^(NSString *userId) {
            NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
        } error:^(RCConnectErrorCode status) {
            NSLog(@"登陆的错误码为:%ld", (long)status);
        } tokenIncorrect:^{
            //token过期或者不正确。
            //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
            //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
            NSLog(@"token错误");
        }];
    }
    
    // 远程推送的内容
    if (launchOptions != nil)
    {
        NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息"
//                                                        message:[NSString stringWithFormat:@"%@",dictionary]
//                                                       delegate:nil
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:nil, nil];
//        [alert show];
        
//        [self.window.rootViewController.tabBarController.tabBar showBadgeOnItemIndex:1];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"TuiSongBage" object:nil];
        
        if (dictionary != nil)
        {
            NSLog(@"Launched from push notification: %@", dictionary);

        }
    }

    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = YES;
    
    // 要使用百度地图，请先启动BaiduMapManager
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:@"kZeZdMlw9XsSWGw9plnQ1ZeC"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"百度启动错误!");
    }
    
    [WXApi registerApp:@"wxd1dfc18de783fc62"];
    
    
    
    // shareSDK
    
    
    /**
     *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册，
     *  在将生成的AppKey传入到此方法中。
     *  方法中的第二个参数用于指定要使用哪些社交平台，以数组形式传入。第三个参数为需要连接社交平台SDK时触发，
     *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
     *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
     */
    [ShareSDK registerApp:@"12f6c424c90e8"
          activePlatforms:@[
                            @(SSDKPlatformTypeQQ),
                            @(SSDKPlatformTypeWechat),
                            @(SSDKPlatformTypeSinaWeibo),
                            
                            ]
                 onImport:^(SSDKPlatformType platformType) {
                     
                     switch (platformType)
                     {
                         case SSDKPlatformTypeWechat:
                            [ShareSDKConnector connectWeChat:[WXApi class]];
//                             [ShareSDKConnector connectWeChat:[WXApi class] delegate:self];
                             break;
                         case SSDKPlatformTypeQQ:
                             [ShareSDKConnector connectQQ:[QQApiInterface class]
                                        tencentOAuthClass:[TencentOAuth class]];
                             break;
                         case SSDKPlatformTypeSinaWeibo:
                             [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                             break;
                         default:
                             break;
                     }
                     
                 }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
              
              switch (platformType)
              {
                  case SSDKPlatformTypeSinaWeibo:
                      //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                      [appInfo SSDKSetupSinaWeiboByAppKey:@"2931462162"
                                                appSecret:@"e4ed7f262efbf377a7d07854b96a9744"
                                              redirectUri:@"http://www.sharesdk.cn"
                                                 authType:SSDKAuthTypeBoth];
                      break;
                      
                  case SSDKPlatformTypeWechat:
                      [appInfo SSDKSetupWeChatByAppId:@"wxd1dfc18de783fc62"
                                            appSecret:@"08aac233dbe8631301a6bf2fb8975813"];
                      break;
                  case SSDKPlatformTypeQQ:
                      [appInfo SSDKSetupQQByAppId:@"1104898161"
                                           appKey:@"GlEjIM7Xx2cb7fgJ"
                                         authType:SSDKAuthTypeBoth];
                      break;
                  default:
                      break;
              }
          }];
    


    return YES;
}

// 启动百度移动统计
- (void)startBaiduMobileStat{
    /*若应用是基于iOS 9系统开发，需要在程序的info.plist文件中添加一项参数配置，确保日志正常发送，配置如下：
     NSAppTransportSecurity(NSDictionary):
     NSAllowsArbitraryLoads(Boolen):YES
     详情参考本Demo的BaiduMobStatSample-Info.plist文件中的配置
     */
    BaiduMobStat* statTracker = [BaiduMobStat defaultStat];
    // 此处(startWithAppId之前)可以设置初始化的可选参数，具体有哪些参数，可详见BaiduMobStat.h文件，例如：
    statTracker.shortAppVersion  = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    statTracker.enableDebugOn = YES;
    
    [statTracker startWithAppId:@"a41fb2d5d4"]; // 设置您在mtj网站上添加的app的appkey,此处AppId即为应用的appKey
}

- (void)applicationWillResignActive:(UIApplication *)application {
    int unreadMsgCount = [[RCIMClient sharedRCIMClient] getUnreadCount:@[
                                                                         @(ConversationType_PRIVATE),
                                                                         @(ConversationType_DISCUSSION),
                                                                         @(ConversationType_APPSERVICE),
                                                                         @(ConversationType_PUBLICSERVICE),
                                                                         @(ConversationType_GROUP)
                                                                         ]];
    application.applicationIconBadgeNumber = unreadMsgCount;
}

- (void)didReceiveMessageNotification:(NSNotification *)notification {
    

        [UIApplication sharedApplication].applicationIconBadgeNumber =
        [UIApplication sharedApplication].applicationIconBadgeNumber + 1;

}

- (void)getUserInfoWithUserId:(NSString *)userId
                   completion:(void (^)(RCUserInfo *userInfo))completion{
    
//    NSLog(@"getUserInfoWithUserId ----- %@", userId);
    
    NSMutableDictionary * muDicParameters = [NSMutableDictionary dictionary];
    
    [muDicParameters setObject:userId forKey:@"account"];
    
    
    if (allConstMemberid) {
        
        [muDicParameters setObject:allConstMemberid forKey:@"MyUserId"];
        
    }
    
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"MyBasicMessage_app_myHome.im"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        
        //        NSString * jsonStr = [LSHttpTool DataTOjsonString:dicInfo];
        //        NSLog(@"--------------------json:%@",jsonStr);
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            RCUserInfo *user = [RCUserInfo new];
            user.userId = userId;
            user.portraitUri = dicInfo[@"data"][@"headPhoto"];
            user.name = dicInfo[@"data"][@"userName"];
            completion(user);
            return;
            
            
        }else {
            
            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];

        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];

}

#pragma mark - 处理推送消息
//- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
//    //应用在前台收到通知
//    NSLog(@"前台========%@", notification);
//}
//
//- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
//    //点击通知进入应用
//    NSLog(@"点击应用进入response:%@", response);
//}

/**
 * 推送处理2
 */
//注册用户通知设置
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
    // register to receive notifications
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
#if TARGET_IPHONE_SIMULATOR
    // 模拟器不能使用远程推送
#else
    // 请检查App的APNs的权限设置，更多内容可以参考文档
    // http://www.rongcloud.cn/docs/ios_push.html。
    NSLog(@"获取DeviceToken失败！！！");
    NSLog(@"ERROR：%@", error);
#endif
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // userInfo为远程推送的内容
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    /**
     * 统计推送打开率2
     */
    [[RCIMClient sharedRCIMClient] recordRemoteNotificationEvent:userInfo];
    /**
     * 获取融云推送服务扩展字段2
     */

//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息"
//                                                    message:[NSString stringWithFormat:@"%@",userInfo]
//                                                   delegate:nil
//                                          cancelButtonTitle:@"确定"
//                                          otherButtonTitles:nil, nil];
//    [alert show];
    
    NSDictionary *pushServiceData = [[RCIMClient sharedRCIMClient]
                                     getPushExtraFromRemoteNotification:userInfo];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"TuiSong" object:nil];
    
    if (pushServiceData) {
        NSLog(@"该远程推送包含来自融云的推送服务");
        for (id key in [pushServiceData allKeys]) {
            NSLog(@"key = %@, value = %@", key, pushServiceData[key]);
        }
    } else {
        NSLog(@"该远程推送不包含来自融云的推送服务");
    }
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"TuiSong" object:nil];
    
    /**
     * 统计推送打开率3
     */
    [[RCIMClient sharedRCIMClient] recordLocalNotificationEvent:notification];
    
    //震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    AudioServicesPlaySystemSound(1007);
}

//监听接收消息的代理
- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left{
    
    
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"TuiSongBage" object:nil];
    
//    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
    
//               dispatch_async(dispatch_get_main_queue(), ^{
    
                   [self.window.rootViewController.tabBarController.tabBar showBadgeOnItemIndex:1];
    
                   //回到主线程刷新界面
                   
//                   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息"
//                                                                   message:@"前台收到本地推送"
//                                                                  delegate:nil
//                                                         cancelButtonTitle:@"确定"
//                                                         otherButtonTitles:nil, nil];
//                   [alert show];
        
//               });
    


//    }

    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {

}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    int unreadMsgCount = [[RCIMClient sharedRCIMClient] getUnreadCount:@[
                                                                         @(ConversationType_PRIVATE),
                                                                         @(ConversationType_DISCUSSION),
                                                                         @(ConversationType_APPSERVICE),
                                                                         @(ConversationType_PUBLICSERVICE),
                                                                         @(ConversationType_GROUP)
                                                                         ]];
    application.applicationIconBadgeNumber = unreadMsgCount;

}


//加入APNs推送，上报deviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSString *token =
    [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                           withString:@""]
      stringByReplacingOccurrencesOfString:@">"
      withString:@""]
     stringByReplacingOccurrencesOfString:@" "
     withString:@""];
    
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];

}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

//将要终止时
- (void)applicationWillTerminate:(UIApplication *)application {
    if ([USER_DEFAULTS objectForKey:@"userid"] == nil) {
        //未登录时，需要清除token
        [USER_DEFAULTS removeObjectForKey:@"token"];
        [USER_DEFAULTS synchronize];
    }
    
    [MagicalRecord cleanUp];
}

@end
